package com.bestcem.xm.member.dao.impl.mysql;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ObjectId;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.common.core.uitls.StringUtil;
import com.bestcem.xm.member.dao.ImportRecordDao;
import com.bestcem.xm.member.dao.mapper.ImportRecordMapper;
import com.bestcem.xm.member.dao.mapper.ImportRecordMsgMapper;
import com.bestcem.xm.member.entity.mongo.ImportRecord;
import com.bestcem.xm.member.entity.mysql.ImportRecordEntity;
import com.bestcem.xm.member.entity.mysql.ImportRecordMsgEntity;
import com.bestcem.xm.member.entity.pojo.ImportRecordDo;
import com.bestcem.xm.member.entity.pojo.ImportRecordMsgDO;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * mysql
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/7/20
 */
@Repository
public class ImportRecordDaoImpl implements ImportRecordDao {

    @Resource
    private ImportRecordMapper importRecordMapper;

    @Resource
    private ImportRecordMsgMapper importRecordMsgMapper;

    @Override
    public ImportRecordDo findOneById(String id) {
        ImportRecordEntity entity = importRecordMapper.findOneById(id);
        return ImportRecordDo.toDo(entity);
    }

    @Override
    public void updateRecordStatus(String id, Integer status) {
        importRecordMapper.updateStatusById(id, status);
    }

    @Override
    public Integer countTotalErrorMsg(String importRecordId) {
        Integer count = importRecordMsgMapper.countByImportRecordId(importRecordId);
        return count;
    }

    @Override
    public List<ImportRecordMsgDO> findTotalErrorMsgPageById(String importRecordId, int start, Integer size) {
        List<ImportRecordMsgEntity> entities = importRecordMsgMapper.findPageByImportRecordId(importRecordId, start, size);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> ImportRecordMsgDO.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public void save(ImportRecordDo record) {
        importRecordMapper.createImportRecord(ImportRecordDo.toEntity(record));
    }

    @Override
    public void updateImportRecordFileName(String recordId, String fileName) {
        importRecordMapper.updateFileNameById(recordId, fileName, DateUtil.getCommonDate());
    }

    @Override
    public void updateImportRecordData(String recordId, Integer receiveCount, Integer successCount, Integer failedCount, JSONArray data, int status) {
        Date updateTime = DateUtil.getCommonDate();
        importRecordMapper.updateCountById(recordId, receiveCount, successCount, failedCount, status, updateTime);
        if (!data.isEmpty()) {
            // 批量插入错误数据
            List<ImportRecordMsgEntity> msgDoList = buildImportRecordMsgList(data, recordId);
            importRecordMsgMapper.batchCreateImportRecordMsg(msgDoList);
        }
    }

    @Override
    public Long countByOrgIdAndUserIdAndAttributeIn(String orgId, String userId, List<Integer> attributes) {
        return importRecordMapper.countByOrgIdAndUserIdAndAttributeIn(orgId, userId, attributes);
    }

    @Override
    public List<ImportRecordDo> findPageByOrgIdAndUserIdAndAttributeIn(String orgId, String userId, List<Integer> attributes, int start, Integer rowsPerPage) {
        List<ImportRecordEntity> entities = importRecordMapper.findPageByOrgIdAndUserIdAndAttributeIn(orgId, userId, attributes, start, rowsPerPage);
        if (CollUtil.isNotEmpty(entities)) {
            return entities.stream().map(entity -> ImportRecordDo.toDo(entity)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public void insertRecordDeatil(String recordId, int line, String message) {
        ImportRecordMsgEntity importRecordMsgEntity = new ImportRecordMsgEntity();
        // id
        importRecordMsgEntity.setId(StringUtil.getId());
        // 导入记录id
        importRecordMsgEntity.setImportId(recordId);
        // 行数
        importRecordMsgEntity.setLine(line);
        // 错误信息
        importRecordMsgEntity.setMessage(message);
        importRecordMsgEntity.setCreateTime(DateUtil.getCommonDate());
        importRecordMsgEntity.setUpdateTime(DateUtil.getCommonDate());
        importRecordMsgMapper.createImportRecordMsg(importRecordMsgEntity);
    }

    private List<ImportRecordMsgEntity> buildImportRecordMsgList(JSONArray data, String recordId) {
        List<ImportRecordMsgEntity> msgDoList = new ArrayList<>(data.size());
        data.forEach(item -> {
            JSONObject itemJson = (JSONObject) JSON.toJSON(item);
            Set<String> keySet = itemJson.keySet();
            keySet.forEach(key -> {
                ImportRecordMsgEntity importRecordMsgEntity = new ImportRecordMsgEntity();
                // id
                importRecordMsgEntity.setId(StringUtil.getId());
                // 导入记录id
                importRecordMsgEntity.setImportId(recordId);
                // 行数
                importRecordMsgEntity.setLine(Integer.parseInt(key));
                // 错误信息
                importRecordMsgEntity.setMessage(itemJson.getString(key));
                importRecordMsgEntity.setCreateTime(DateUtil.getCommonDate());
                importRecordMsgEntity.setUpdateTime(DateUtil.getCommonDate());
                msgDoList.add(importRecordMsgEntity);
            });
        });
        return msgDoList;
    }

    private List<ImportRecordMsgEntity> convertMsg(ImportRecord importRecord){
        List<ImportRecordMsgEntity> res = new ArrayList<>();

        if(importRecord.getData() == null || importRecord.getData().isEmpty()){
            return res;
        }

        JSONArray jsonArray = importRecord.getData().getJSONArray("total_error_msg");
        if(jsonArray == null || jsonArray.isEmpty()){
            return res;
        }

        for(Object object : jsonArray){
            if(!(object instanceof Map)){
                continue;
            }
            Map<String, Object> jsonObject = (Map)object;
            if(jsonObject.entrySet().isEmpty()){
                continue;
            }
            ImportRecordMsgEntity entity = new ImportRecordMsgEntity();
            entity.setId(ObjectId.next());
            entity.setImportId(importRecord.getId());
            for(Map.Entry<String, Object> entry : jsonObject.entrySet()){
                if(StringUtils.hasText(entry.getKey())){
                    entity.setLine(Integer.parseInt(entry.getKey()));
                }
                if(entry.getValue() != null){
                    entity.setMessage(entry.getValue().toString());
                }
                break;
            }
            entity.setCreateTime(importRecord.getCreateTime());
            entity.setUpdateTime(importRecord.getUpdateTime());
            res.add(entity);
        }

        return res;
    }
}
